<?php
/**
 * Created by PhpStorm.
 * User: tushengxiang
 * Date: 2019/5/27
 * Time: 9:35 AM
 */
namespace App\Http\Controllers\ClassVoice\Voice;

use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class ClassController extends Controller {

    public function index(Request $request)
    {


        return view('ClassVoice.voiceClass');
    }

    public function pay(Request $request) {
        //授权获取openID
        $openid = $this->oAuth($request);

        $config = [
            'app_id' => 'wx6da8ff44e136e5f9',
            'secret' => '9e56e0c6c4d82a3e94e765b8a31ea528',

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            //...
        ];

        //$app = Factory::officialAccount($config);


        $config = [
            // 前面的appid什么的也得保留哦
            'app_id'             => 'wx6da8ff44e136e5f9',
            'mch_id'             => '1516199541',
            'key'                => 'h78hfqew78hdsh9uojtbsgvy89u0pobd',
            'cert_path'          => storage_path('cert/apiclient_cert.pem'), // XXX: 绝对路径！！！！
            'key_path'           => storage_path('cert/apiclient_key.pem'),      // XXX: 绝对路径！！！！
            'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它
            // 'device_info'     => '013467007045764',
            // 'sub_app_id'      => '',
            // 'sub_merchant_id' => '',
            // ...
        ];

        $app = Factory::payment($config);
        $result = $app->order->unify([
            'body' => 'test-recharge',
            'out_trade_no' => date('YmdHis'),
            'total_fee' => 1,
            //'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => 'http://'.env('VOICE_CLASS').'/voice/payCallBack', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
       /*var_dump($result);
       return;*/
        $prepayId = $result['prepay_id'];
        //return;
        $jssdk = $app->jssdk;
        $pay_info = $jssdk->bridgeConfig($prepayId,false); // 返回 json 字符串，如果想返回数组，传第二个参数 false
        //var_dump($pay_info);
        return view('ClassVoice.voiceClass',compact('pay_info'));
    }

    public function payCallBack(Request $request){
        $res = file_get_contents("php://input");
        \Log::info(var_export($res,true));
    }

    public function voiceClassList(Request $request)
    {
        return view('ClassVoice.voiceClassList');
    }

    public function voiceClassContent(Request $request)
    {
        return view('ClassVoice.voiceContent');
    }

    public function voiceClassShare(Request $request)
    {
        return view('ClassVoice.VoiceShare');
    }

    public function voiceIndex(Request $request)
    {
        return view('ClassVoice.VoiceIndex');
    }

    public function voiceUnpaid(Request $request)
    {
        return view('ClassVoice.VoiceUnpaid');
    }

    private function oAuth(Request $request) {
        $openid= $request->session()->get('userInfo','');

        if (empty($openid)) {
            $openid = $request->input('oid', '');
            if ($openid) {

                $request->session()->push('openid', $openid);
                return $openid;
            } else {


                $scope = 'snsapi_base';  // 或者 snsapi_base

                $keys       = 'PayAppID,PayAppSecret,PayWxHao,MAIN_DOMAIN,PayURL,FORCE_AUTH';
                /*$config_obj = new Config();
                $config_arr = $config_obj->getConfigs($keys);*/

                //$url = $config_arr['PayURL'].'user/auth';
                $url         = "http://api.zkh168.com/" . 'user/auth';
                $main_domain = $_SERVER['HTTP_HOST'];//$config_arr['MAIN_DOMAIN'];
                $return_url  = urlencode('http://' . $main_domain . $_SERVER["REQUEST_URI"]);

                $args               = array();
                $args['timestamp']  = time();
                $args['app_id']     = 'qun_yujia';//$config_arr['PayAppID'];
                $args['app_secret'] = 'c36f10fd0ff59c3bcce088d7a7a6c410';//$config_arr['PayAppSecret'];
                $args['next_url']   = $return_url;
                $args['scope']      = $scope;
                $force_auth         = 0;
                $args['force_auth'] = $force_auth;

                $sign = $this->getSign($args);

                unset($args['app_secret']);
                $args_str = array();
                foreach ($args as $k => $v) {
                    $args_str[] = $k . '=' . $v;
                }
                $arg_str = implode('&', $args_str);

                $url .= '?' . $arg_str . '&sign=' . $sign;
               // print_r($url);
                $this->redirect($url);
                //return '33333';
                die;
            }
        } else {
            //$this->uid      = $userInfo['id'] ? $userInfo['id'] : session('uid');
            return $request->session()->get('openid','nooooooo');
            //$this->userInfo = $userInfo;
        }
    }

    private function getSign($args)
    {
        $tmpArr = array();
        foreach ($args as $arg){
            $tmpArr[]= $arg;
        }
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        return $tmpStr;
    }

    private function redirect($url, $time = 0, $msg = '')
    {
        //多行URL地址支持
        $url = str_replace(array("\n", "\r"), '', $url);
        if (empty($msg)) {
            $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
        }

        if (!headers_sent()) {
            // redirect
            if (0 === $time) {
                header('Location: ' . $url);
            } else {
                header("refresh:{$time};url={$url}");
                echo ($msg);
            }
            exit();
        } else {
            $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if (0 != $time) {
                $str .= $msg;
            }

            exit($str);
        }
    }
}